import { getSideBarData } from '@/components/helpCenter/model/sidebarData';
import ElMessage from '@/utils/message';
import { encryption } from '@/utils';
import avatarPng from '@/assets/todo/avatar.png';
import { taskType as getTaskType, flowStatus, contractType, getColor, todoList, modifyStatus,
  flowStatusColor, modifyStatusColor, customerCooStatus, customerCooColor } from '@/filters/status';
import { isJSON } from '@/utils/tools';
import { hasRouteAuth } from '@/utils/permission';
import { SUPPLIER_DETAIL_TYPE } from '@/utils/const/supplier';

export default {
  filters: { getTaskType },
  data() {
    return {
      avatarPng,
      newTabOpen: false,
      fromTodo: true
    };
  },
  computed: {
    sidebarData() {
      const list = getSideBarData();
      return list;
    },
    taskType() {
      return [
        { value: -1, label: '其他审批' },
        { value: 0, label: '合同审批' },
        { value: 1, label: '付款申请' },
        { value: 2, label: '部门通知' },
        { value: 3, label: '评论' },
        { value: 4, label: '帮助文章' },
        { value: 5, label: '抄送' },
        { value: 6, label: '精力分配' },
        { value: 7, label: '签约内审' },
        { value: 8, label: '信息修改' },
        { value: 9, label: '申请原件' },
        { value: 10, label: '开票申请' },
        { value: 11, label: '发票作废' },
        { value: 12, label: '交接管理' },
        { value: 13, label: '还款申请' },
        { value: 14, label: '员工报销' },
        { value: 15, label: '借款申请' },
        { value: 18, label: '每月结算' },
        { value: 19, label: '转交欠款' },
        { value: 20, label: '达人解约' },
        { value: 21, label: '客户调额申请' },
        { value: 22, label: '外采额度申请' },
        { value: 23, label: '风险监控预警' },
        { value: 24, label: '客户协作申请' },
        { value: 25, label: '达人初筛' },
        { value: 26, label: '达人上刊' }
      ];
    },
    flowStatusOptions() {
      return [
        { value: 1, label: '审批中' },
        { value: 2, label: '未过审' },
        { value: 3, label: '已作废' },
        { value: 4, label: '已完成' },
        { value: 5, label: '已撤回' }
      ];
    },
    filterList() {
      return [
        { keyword: 'abstract', name: '摘要', labelWidth: '85px', type: 'input' },
        { keyword: 'proposerName', name: '发起人', labelWidth: '85px', type: 'input' },
        { keyword: 'currentNode', name: '当前节点', labelWidth: '85px', type: 'input' },
        { keyword: 'approvers', name: '当前处理人', labelWidth: '85px', type: 'input' },
        { keyword: 'type', name: '任务类型', type: 'select', options: this.taskType },
        { keyword: 'status', name: '流程状态', type: 'select', options: this.flowStatusOptions },
        { keyword: 'createTime', name: '发起时间', labelWidth: '85px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'approveTime', name: '审批时间', labelWidth: '85px', timeType: 'daterange', type: 'rangeDate' }
      ];
    },
    rangeKeyArr() {
      return [{
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }, {
        attr: 'approveTime',
        start: 'approveStart',
        end: 'approveEnd',
        type: 'time'
      }];
    },
    // 类型对应跳转方法配置
    typeToPageParams() {
      return new Map([
        [-1, this.toCustomProcess], // 跳转至自定义审批
        [0, this.toContract], // 跳转至对应合同审批
        [1, this.toSupplier], // 跳转至对应请款单
        [2, this.toTodoDetail], // 跳转至部门通知详情
        [4, this.toHelp], // 跳转至对应帮助文章
        [6, this.toEnergy], // 跳转至精力分配详情
        [7, this.toSignUp], // 跳转至签约内审
        [8, this.toSupplierManageDetail], // 跳转至信息修改
        [9, this.toOriginal], // 跳转至申请原件详情
        [10, this.toIssueInvoice], // 跳转至开票申请
        [11, this.toInvoiceAbandon], // 跳转至发票作废
        [12, this.toHandoverDetail], // 跳转至交接管理详情
        [13, this.toPayBack], // 跳转至还款申请详情
        [14, this.toReimbursement], // 跳转员工报销详情
        [15, this.toLoan], // 跳转至借款申请详情
        [18, this.toBatchSettle], // 跳转至智能结算
        [19, this.toArrearsTransferDetail], // 跳转至转交欠款详情
        [20, this.toTermination], // 跳转至达人解约详情
        [21, this.toCustomerAdjustmentDetail], // 跳转客户调额申请
        [22, this.toExternalHarvest], // 跳转至外采额度申请详情
        [23, this.toRiskDetail], // 跳转至风险监控对应详情
        [24, this.toCustomerCooperationDetail], // 跳转客户协作申请
        [25, this.toFilterDetail], // 跳转达人初筛详情
        [26, this.toUpOnlineDetail] // 跳转达人上刊详情
      ]);
    }
  },
  methods: {
    getColor,
    todoList,
    isJSON,
    hasRouteAuth,
    modifyStatus,
    flowStatus,
    getTaskType,
    contractType,
    flowStatusColor,
    modifyStatusColor,
    customerCooStatus,
    customerCooColor,
    formatNull(str) {
      return str === 'null' ? '--' : str;
    },
    formatTime(timeStr) {
      if (timeStr) {
        const time = new Date(timeStr).getTime();
        return moment(time).format('YYYY/MM/DD').toString();
      } else {
        return '--';
      }
    },
    monthNum(row) {
      return row.month ? `${row.month.slice(-2)}` : '';
    },
    formatTitle(data) {
      if (this.activeId === 'notice') {
        return data.title;
      } else if (data.type === 6) {
        return '你有' + this.monthNum(data) + '月份精力分配待处理';
      } else if (data.type === -1) { // 自定义（其他）审批
        return data.proposerName + '提交的' + data.moduleName || '其他审批';
      } else if (data.proposerName) {
        return data.proposerName + '提交的' + this.getTaskType(data.type);
      } else {
        return '--';
      }
    },
    formatStatus(data, activeId) {
      const res = {};
      if ([2, 16, 18, 23].includes(data.type) && this.activeId === activeId) {
        res.color = this.flowStatusColor(6);
        res.status = '系统通知';
      } else if (data.type === 4 && this.activeId === activeId) {
        res.color = this.flowStatusColor(6);
        res.status = '文章';
      } else if (data.type === 12 && this.activeId === activeId) {
        res.color = this.flowStatusColor(4);
        res.status = '已完成';
      } else if (data.type === 8) {
        res.color = this.modifyStatusColor(data.status);
        res.status = this.modifyStatus(data.status);
      } else if (data.type === 24) {
        res.color = this.customerCooColor(data.status);
        res.status = this.customerCooStatus(data.status);
      } else {
        res.color = this.flowStatusColor(data.status);
        res.status = this.flowStatus(data.status);
      }
      return res;
    },
    showField(field, data) {
      let flag = null;
      if (data.hasOwnProperty(field) && data[field]) {
        flag = true;
      }
      if (field === 'modifyRemark') {
        flag = flag && !data.status;
      }
      if (field === 'approvalReason') { // 等后端不返回审批理由,就可以去掉
        return flag && data.status;
      }
      return flag;
    },
    getHelpModule(key) {
      const aryOptions = { 'newRead': '新手必读', 'announce': '公告' };
      const sidebarData = this.sidebarData;
      for (let i = 0; i < sidebarData.length; i++) {
        sidebarData[i].children.forEach(item => {
          aryOptions[item.name] = `${sidebarData[i].label}-${item.label}`;
        });
      }
      return aryOptions[key];
    },
    // 页面跳转
    handleJumpPage(params) {
      if (this.newTabOpen) { // 是否新页面打开
        const routeUrl = this.$router.resolve(params);
        window.open(routeUrl.href, '_blank');
      } else {
        this.$router.push(params);
      }
    },
    toContract(row) {
      if (this.hasRouteAuth('crm:contract:read')) {
        const query = { processId: encryption(row.processId) };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'contractDetail',
          params: { id: encryption(row.businessId) },
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无合同审批可读权限，请联系管理员添加');
      }
    },
    toSupplier(row) {
      if (this.hasRouteAuth('medium:supplierAudit:read')) {
        const query = { settleId: row.businessId, id: row.processId, isSettle: true };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'supplierDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无结算查看可读权限，请联系管理员添加');
      }
    },
    toEnergy(row) {
      if (this.hasRouteAuth('energy:energyList:read')) {
        const query = { energyId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'energyDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无精力分配可读权限，请联系管理员添加');
      }
    },
    toSignUp(row) {
      if (this.hasRouteAuth('signUp:signUp:read')) {
        const query = { signUpId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'signUpDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无签约内审可读权限，请联系管理员添加');
      }
    },
    toIssueInvoice(row) {
      if (this.hasRouteAuth('invoice:issue:read')) {
        const query = { issueId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'issueInvoiceDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无开票申请可读权限，请联系管理员添加');
      }
    },
    toReimbursement(row) {
      if (this.hasRouteAuth('crm:reimbursement:read')) {
        const query = { reimbursementId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'reimbursementDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无员工报销可读权限，请联系管理员添加');
      }
    },
    toOriginal(row) {
      if (this.hasRouteAuth('crm:original:read')) {
        const query = { originalId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'originalDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无申请原件可读权限，请联系管理员添加');
      }
    },
    toLoan(row) {
      if (this.hasRouteAuth('crm:loan:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'loanDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无借款申请可读权限，请联系管理员添加');
      }
    },
    toArrearsTransferDetail(row) {
      if (this.hasRouteAuth('crm:arrearsTransfer:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'arrearsTransferDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无转交欠款可读权限，请联系管理员添加');
      }
    },
    toTermination(row) {
      if (this.hasRouteAuth('crm:termination:read')) {
        const query = { terminationId: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'terminationDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无达人解约可读权限，请联系管理员添加');
      }
    },
    toExternalHarvest(row) {
      if (this.hasRouteAuth('crm:externalHarvest:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'externalHarvestDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无外采额度申请可读权限，请联系管理员添加');
      }
    },
    toPayBack(row) {
      if (this.hasRouteAuth('crm:payBack:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'payBackDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无还款申请可读权限，请联系管理员添加');
      }
    },
    toSupplierManageDetail(row) {
      if (this.hasRouteAuth('medium:supplier:read')) {
        const routerParams = {
          name: 'supplierManageDetail',
          query: { type: SUPPLIER_DETAIL_TYPE.MODIFY },
          params: { id: row.businessId }
        };
        this.fromTodo && (routerParams.query.fromTodo = 1);
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无销售供应商可读权限，请联系管理员添加');
      }
    },
    toInvoiceAbandon(row) {
      if (this.hasRouteAuth('invoice:abandon:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'invoiceAbandonDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无发票作废可读权限，请联系管理员添加');
      }
    },
    toCustomerAdjustmentDetail(row) {
      if (this.hasRouteAuth('crm:customerAdjustment:read')) {
        const routerParams = {
          name: 'customerAdjustmentDetail',
          query: {
            id: row.businessId,
            processId: row.processId
          }
        };
        this.fromTodo && (routerParams.query.fromTodo = 1);
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无客户调额申请可读权限，请联系管理员添加');
      }
    },
    toCustomerCooperationDetail(row) {
      if (this.hasRouteAuth('crm:customer:read')) {
        const content = this.strJsonParse(row.content);
        const routerParams = {
          name: 'cooperation',
          query: { approvalNo: content['审批单号'] }
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无客户协作申请可读权限，请联系管理员添加');
      }
    },
    toFilterDetail(row) {
      if (this.hasRouteAuth('crm:filter:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        if (row.type === 3) query.openComment = 1;
        const routerParams = {
          name: 'filterDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无达人初筛可读权限，请联系管理员添加');
      }
    },
    toUpOnlineDetail(row) {
      if (this.hasRouteAuth('crm:upOline:read')) {
        const query = { id: row.businessId, processId: row.processId };
        this.fromTodo && (query.fromTodo = 1);
        const routerParams = {
          name: 'upOnlineDetail',
          query
        };
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无达人上刊可读权限，请联系管理员添加');
      }
    },
    toHandoverDetail(row) {
      if (this.hasRouteAuth('auth:handover:read')) {
        const routerParams = {
          name: 'handoverDetail',
          params: { id: row.businessId }
        };
        this.fromTodo && (routerParams.query = { fromTodo: 1 });
        this.handleJumpPage(routerParams);
      } else {
        ElMessage.warning('当前用户暂无交接管理可读权限，请联系管理员添加');
      }
    },
    toHelp(row) {
      if (this.hasRouteAuth(['crm:help:add', 'crm:help:edit', 'crm:help:del'])) {
        const routerParams = {
          name: 'helpDetail',
          params: { id: row.businessId },
          query: { model: row.module }
        };
        this.fromTodo && (routerParams.query.fromTodo = 1);
        const url = this.$router.resolve(routerParams);
        window.open(url.href, '_blank');
      } else {
        ElMessage.warning('当前用户暂无帮助中心权限，请联系管理员添加');
      }
    },
    toTodoDetail(row) {
      const params = { id: row.id };
      const query = { todoList: row.reportModule, type: row.type };
      if (row.type === 18) {
        query.followUsers = row.followUsers;
        params.id = row.businessId;
      }
      const routerParams = {
        name: 'todoDetail',
        params,
        query
      };
      this.fromTodo && (routerParams.query.fromTodo = 1);
      this.$router.push(routerParams);
    },
    toBatchSettle(row) {
      const params = {};
      try {
        const content = JSON.parse(row.content);
        if (content['下单日期']) {
          const timeArr = content['下单日期'].split('-');
          if (timeArr && timeArr.length === 2) {
            params.startTime = timeArr[0];
            params.endTime = timeArr[1];
          }
        }
      } catch (error) {
        console.log(error);
      }
      const routerParams = {
        name: 'batchSettle',
        query: params
      };
      this.handleJumpPage(routerParams);
    },
    toCustomProcess(row) {
      const query = { id: row.businessId, processId: row.processId };
      this.fromTodo && (query.fromTodo = 1);
      if (row.type === 3) query.openComment = 1;
      const routerParams = {
        name: 'approvalModuleDetail',
        params: { moduleId: row.moduleId },
        query
      };
      this.handleJumpPage(routerParams);
    },
    toRiskDetail(row) {
      window.open(row.jumpLink, '_blank');
    },
    toDetail(row, fromTodo = true) {
      this.setSingleRead && this.setSingleRead(row);
      // 跳转至评论详情&跳转至抄送详情时特殊处理
      this.fromTodo = fromTodo;
      const typeKey = [3, 5, 16, 17].includes(row.type) ? 'moduleType' : 'type';
      const callbackFun = this.typeToPageParams.get(row[typeKey]);
      callbackFun && callbackFun(row);
      if (this.$refs.todoPopper) {
        this.$refs.todoPopper.doClose();
      }
    },
    formatAbstractData(str) {
      const data = this.strJsonParse(str);
      if (data['模块']) {
        data['模块'] = this.getHelpModule(data['模块']);
      }
      return data;
    },
    getDetailLink(row) {
      const { processId, businessId, moduleId } = row;
      const linkMap = new Map([
        [0, `legal/contractDetail/${encryption(businessId)}?processId=${encryption(processId)}`],
        [1, `businessPage/supplierDetail?settleId=${businessId}&id=${processId}&isSettle=true`],
        [2, `operate/energy/detail?energyId=${businessId}&processId=${processId}`],
        [3, `supplierPage/signUpDetail?signUpId=${businessId}&processId=${processId}`],
        [4, `legal/originalDetail?originalId=${businessId}&processId=${processId}`],
        [5, `businessPage/issueInvoiceDetail?issueId=${businessId}&processId=${processId}`],
        [6, `businessPage/invoiceAbandonDetail?id=${businessId}&processId=${processId}`],
        [7, `businessPage/reimbursementDetail?reimbursementId=${businessId}&processId=${processId}`],
        [8, `businessPage/loanDetail?id=${businessId}&processId=${processId}`],
        [9, `businessPage/payBackDetail?id=${businessId}&processId=${processId}`],
        [10, `homePage/approvalModuleDetail/${moduleId}?id=${businessId}&processId=${processId}`],
        [11, `businessPage/arrearsTransferDetail?id=${businessId}&processId=${processId}`],
        [12, `supplierPage/terminationDetail?terminationId=${businessId}&processId=${processId}`],
        [13, `client/customerAdjustmentDetail?id=${businessId}&processId=${processId}`],
        [14, `orderPage/externalHarvestDetail?id=${businessId}&processId=${processId}`],
        [15, `supplierPage/filterDetail?id=${businessId}&processId=${processId}`],
        [16, `supplierPage/upOnlineDetail?id=${businessId}&processId=${processId}`]
      ]);
      const link = `${location.origin}#/${linkMap.get(row.type)}` || '--';
      return link;
    }
  }
};
